<template>
  <div class="canvas-editor">
    <div class="toolbar">
      <van-button @click="handleFlipY">垂直翻转</van-button>
      <van-button @click="handleRotate">旋转</van-button>
      <van-button @click="undo" :disabled="!canUndo">撤销</van-button>
      <van-button @click="redo" :disabled="!canRedo">重做</van-button>
      <!-- <van-uploader :after-read="handleFileUpload" accept="image/*">
        <van-button>上传图片</van-button>
      </van-uploader>-->
      <input type="file" @change="handleImageUpload" accept="image/*" />
    </div>
    <div class="index">
      <div class="canvas" id="canvas" ref="canvasRef"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";

import Konva from "konva";
import { create } from "domain";
const canvasRef = ref<HTMLCanvasElement | null>(null);
let imgNode: Konva.Image | null = null;
let stage: Konva.Stage;
const layer: Konva.Layer = new Konva.Layer();

const tr: Konva.Transformer = new Konva.Transformer();
const selectedNode = ref<Konva.Image>(); // 新增选中节点引用
const scaleFactor = 1.1; // 缩放系数

let currentGroup: Konva.Group | null = null;
const stageSize = { width: 300, height: 300 };
const handleSize = 10;
const maxImageSize = 150;

// 手柄元素
let handles: Konva.Circle[] = [];
// 手柄元素
let topLeftHandle: Konva.Rect;
let topRightHandle: Konva.Rect;
let bottomRightHandle: Konva.Rect;
let bottomLeftHandle: Konva.Rect;
const handleRotate = () => {
  if (imgNode) {
    // 每次旋转90度（基于当前旋转角度）
    const currentRotation = imgNode.rotation();

    imgNode.rotation((currentRotation + 90) % 360);
    layer.batchDraw();
  }
};
const handleFlipY = () => {
  if (imgNode) {
    // 简化翻转逻辑，直接修改scaleX并调整位置
    // const currentScale = imgNode.scaleX();
    // imgNode.scaleX(-currentScale);
    // 调整位置保持图片中心不变
    // imgNode.x(imgNode.x() + imgNode.width() * currentScale);
    imgNode.scaleX(imgNode.scaleX() * -1);
    layer.batchDraw();
  }
}; // 新增翻转Y轴功能

const init = () => {
  const el = document.getElementById("canvas");
  if (!el) {
    return;
  }

  const { clientWidth, clientHeight } = el;
  const stage = new Konva.Stage({
    container: "canvas",
    width: clientWidth,
    height: clientHeight
  });

  const layer = new Konva.Layer();
  stage.add(layer);

  Konva.Image.fromURL("/src/assets/tabbar/edit.png", (image: Konva.Image) => {
    image.setAttrs({
      x: clientWidth / 2 - 25,
      y: clientHeight / 2 - 25,
      height: 50,
      width: 50,
      scaleY: 1,
      scaleX: 1
    });

    layer.add(image);
  });
};
const handleImageUpload = (e: Event) => {
  const file = (e.target as HTMLInputElement).files?.[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = e => {
      const image = new Image();
      image.src = e.target?.result as string;
      image.onload = () => createImage(image);
      // image.onload = () => {
      //   const group = new Konva.Group();

      //   imgNode = new Konva.Image({
      //     image: image,
      //     draggable: true,
      //     x: 50,
      //     y: 50,
      //     width: 100,
      //     height: 100,
      //     offset: {
      //       // offset的设置是使得围绕中心旋转：x:50,y:50
      //       x: 50,
      //       y: 50
      //     }
      //   });
      //   console.log("imgNode", imgNode);

      //   layer.add(imgNode);

      //   console.log("imgNode.x", imgNode.x()); //70
      //   console.log("imgNode.widdth()", imgNode.width()); //100

      //   // 创建右下角旋转手柄
      //   const rotateHandle = new Konva.Circle({
      //     // x: 120,  // 初始位置：x + width
      //     // y: 120,  // 初始位置：y + height
      //     x: imgNode.width(), // 初始位置：x + width
      //     y: imgNode.height(), // 初始位置：y + height
      //     radius: 8,
      //     fill: "rgba(255,0,0,0.6)",
      //     draggable: true
      //   });

      //   // 新增组变换监听
      //   group.on("transform dragmove", () => {
      //     rotateHandle.position({
      //       x: imgNode.width(),
      //       y: imgNode.height()
      //     });
      //   });

      //   // 旋转逻辑
      //   let startAngle = 0;
      //   rotateHandle.on("dragstart", () => {
      //     const absPos = group.getAbsolutePosition();
      //     console.log("点击手柄", absPos);
      //     const center = {
      //       x: absPos.x + imgNode.width() / 2,
      //       y: absPos.y + imgNode.height() / 2
      //     };
      //     const pos = rotateHandle.getStage()?.getPointerPosition();
      //     console.log("pos", pos);
      //     if (pos) {
      //       const newAngle = Math.atan2(pos.y - center.y, pos.x - center.x);
      //       if (e.type === "dragstart") {
      //         startAngle = newAngle;
      //       } else {
      //         imgNode.rotation((newAngle - startAngle) * (180 / Math.PI));
      //         layer.batchDraw();
      //       }
      //     }
      //   });

      //   rotateHandle.on("dragmove", () => {
      //     console.log("移动手柄");
      //     const center = {
      //       x: imgNode.x() + imgNode.width() / 2,
      //       y: imgNode.y() + imgNode.height() / 2
      //     };
      //     const pos = rotateHandle.getStage()?.getPointerPosition();
      //     if (pos) {
      //       const newAngle = Math.atan2(pos.y - center.y, pos.x - center.x);
      //       imgNode.rotation((newAngle - startAngle) * (180 / Math.PI));
      //       layer.batchDraw();
      //     }
      //   });

      //   // 将图片和手柄组合

      //   group.add(imgNode);
      //   group.add(rotateHandle);
      //   layer.add(group);

      //   // var triggerTime = -1000;
      //   // var scale = 1;
      //   // var angularSpeed = 190;
      //   // var anim = new Konva.Animation(function(frame: any) {
      //   //     if (frame.time - triggerTime < 1000){
      //   //         return false;
      //   //     }

      //   //     triggerTime = frame.time;

      //   //     var angleDiff = frame.timeDiff * angularSpeed / 1000;
      //   //     scale *= -1;
      //   //     imgNode.scale({x: scale, y: 1});
      //   //     // kImage1.rotate(angleDiff);          // 旋转
      //   //     // kImage2.scale({x: scale, y: 1});    // 左右镜像
      //   //     // kImage3.scale({x: 1, y: scale});    // 上下翻转
      //   // }, layer);
      //   // anim.start();
      //   // saveHistory('上传图片');
      // };
    };
    reader.readAsDataURL(file);
  }
  function createImage(img: HTMLImageElement) {
    // 计算缩放比例
    console.log("img", img.width, img.height);
    const scale = Math.min(maxImageSize / img.width, maxImageSize / img.height);
    const group = new Konva.Group({
      x: stageSize.width / 2, // 初始位置：从这里开始画
      y: stageSize.height / 2,
      width: 100,
      height: 100,
      offsetX: (img.width * scale) / 2, //中心点
      offsetY: (img.height * scale) / 2,
      draggable: true // 添加可拖动属性
    });
    // 添加组点击事件
    group.on("click tap", (e) => {
      e.cancelBubble = true; // 阻止事件冒泡
      currentGroup = group;
      showHandles();
    });
    const konvaImg = new Konva.Image({
      image: img,
      width: img.width * scale, // 按比例缩放图片
      height: img.height * scale
    });
    const border = new Konva.Rect({
      width: konvaImg.width(),
      height: konvaImg.height(),
      stroke: "#0099ff",
      strokeWidth: 2,
      dash: [4, 4]
    });
    group.add(konvaImg, border);
    layer.add(group);
    createHandles(group);
  }

  function createHandles(group: Konva.Group) {
    console.log("createHandles", group);

    // // 创建四个手柄
    // const handlePositions = [
    //   { color: '#ff4444', position: 'top-left', poitX:10,poitY:10, onClick: () => deleteImage() },
    //   { color: '#00ff00', position: 'top-right',poitX:40,poitY:10, },
    //   { color: '#2196F3', position: 'bottom-right',poitX:40,poitY:40, },
    //   { color: '#ffeb3b', position: 'bottom-left',poitX:10,poitY:40, onClick: () => flipVertical(group) }
    // ];

    // 获取图片组实际渲染尺寸
    const rect = group.getClientRect();
    // console.log("rect", rect);
    const imgWidth = rect.width;
    const imgHeight = rect.height;

    // 基于组中心坐标系计算四角坐标
    const handlePositions = [
      {
        // 左上角（相对组中心）
        x: 0,
        y: 0,
        color: "#ff4444",
        onClick: () => {
          // 修复顺序：先移除再销毁
          group.remove();
          group.destroy();
          destroyHandles();
          currentGroup = null;

          // 强制清理舞台
          layer.draw();
          stage.batchDraw();

          // 重置上传输入 防止删除后无法重新上传图片
          const fileInput = document.querySelector(
            'input[type="file"]'
          ) as HTMLInputElement;
          if (fileInput) {
            fileInput.value = ""; // 清除已选文件
          }
        }
      },
      {
        // 右上角
        x: imgWidth,
        y: 0,
        color: "#00ff00"
      },
      {
        // 右下角
        x: imgWidth,
        y: imgHeight,
        color: "#2196F3"
      },
      {
        // 左下角
        x: 0,
        y: imgHeight,
        color: "#ffeb3b",
        onClick: () => flipVertical(group)
      }
    ];

    handles = handlePositions.map(pos => {
      const handle = new Konva.Circle({
        x: pos.x,
        y: pos.y,
        radius: handleSize,
        fill: pos.color,
        draggable: true,
        visible: true,
        stroke: "white",
        strokeWidth: 2
      });

      if (pos.onClick) {
        handle.on("click tap", e => {
          e.cancelBubble = true; // 阻止事件冒泡
          pos.onClick!();
        });
      }
      group.add(handle); // 新增手柄到组中
      // layer.add(handle);
      return handle;
    });

    // 设置操作手柄功能
    setupRotationHandle(handles[1], group); // 右上旋转
    setupScaleHandle(handles[2], group); // 右下缩放
  }

  function setupGroupEvents(group: Konva.Group) {
    group.on("dragmove", () => {
      updateBorderAndHandles();
      layer.batchDraw();
    });

    group.on("click", () => {
      showHandles();
      group.findOne("Rect")?.visible(true);
    });
  }

  function setupRotationHandle(handle: Konva.Circle, group: Konva.Group) {
    let lastAngle = 0;

    handle.on("dragstart", () => {
      const center = group.getAbsolutePosition();
      const pos = stage.getPointerPosition()!;
      lastAngle = Math.atan2(pos.y - center.y, pos.x - center.x);
    });

    handle.on("dragmove", () => {
      const center = group.getAbsolutePosition();
      const pos = stage.getPointerPosition()!;
      const newAngle = Math.atan2(pos.y - center.y, pos.x - center.x);

      group.rotation(
        group.rotation() + (newAngle - lastAngle) * (180 / Math.PI)
      );
      lastAngle = newAngle;
      updateBorderAndHandles();
    });
  }

  function setupScaleHandle(handle: Konva.Circle, group: Konva.Group) {
    let startScale = 1;
    let startDistance = 0;

    handle.on("dragstart", () => {
      const center = group.getAbsolutePosition();
      const pos = stage.getPointerPosition()!;
      startScale = group.scaleX();
      startDistance = Math.hypot(pos.x - center.x, pos.y - center.y);
    });

    handle.on("dragmove", () => {
      const center = group.getAbsolutePosition();
      const pos = stage.getPointerPosition()!;
      const currentDistance = Math.hypot(pos.x - center.x, pos.y - center.y);

      const scaleFactor = currentDistance / startDistance;
      const newScale = startScale * scaleFactor;

      group.scaleX(newScale);
      group.scaleY(newScale);
      updateBorderAndHandles();
    });
  }

  function updateBorderAndHandles() {
    console.log("updateBorderAndHandles",currentGroup);
    if (!currentGroup) return;

    const rect = currentGroup.getClientRect();
    const border = currentGroup.findOne("Rect");

    // 更新边框
    if (border) {
      border.width(rect.width);
      border.height(rect.height);
      border.visible(true);
    }
    console.log("rect", rect);
    // 更新手柄位置
    const center = currentGroup.getAbsolutePosition();
    console.log("center", center);
    const corners = [
      { x: rect.width, y: rect.height }, // top-left
      { x: rect.width, y: rect.height }, // top-right
      { x: rect.width, y: rect.height }, // bottom-right
      { x: rect.width, y: rect.height } // bottom-left
    ];

    handles.forEach((handle, index) => {
      const corner = corners[index];
      const rotatedPoint = rotatePoint(
        corner.x,
        corner.y,
        currentGroup!.rotation()
      );

      handle.position({
        x: center.x + rotatedPoint.x,
        y: center.y + rotatedPoint.y
      });
    });

    layer.batchDraw();
  }

  function rotatePoint(x: number, y: number, degrees: number) {
    const radians = Konva.getAngle(degrees);
    return {
      x: x * Math.cos(radians) - y * Math.sin(radians),
      y: x * Math.sin(radians) + y * Math.cos(radians)
    };
  }

  function showHandles() {
    handles.forEach(h => h.visible(true));
    layer.batchDraw();
  }

  function hideHandles() {
    handles.forEach(h => h.visible(false));
    if (currentGroup) {
      currentGroup.findOne("Rect")?.visible(false);
    }
    layer.batchDraw();
  }

  function deleteImage() {
    currentGroup?.destroy();
    // 清空当前组引用
    currentGroup = null;
    // destroyHandles();
    layer.batchDraw();
  }

  function flipVertical(group: Konva.Group) {
    console.log("flipVertical", group);
    group.scaleY(-group.scaleY());
    updateBorderAndHandles();
  }

  function destroyHandles() {
    handles.forEach(h => h.destroy());
    handles = [];
  }
};
const showHandles = () => {
  handles.forEach(h => h.visible(true));
  layer.batchDraw();
};

const hideHandles = () => {
  handles.forEach(h => h.visible(false));
  if (currentGroup) {
    currentGroup.findOne("Rect")?.visible(false);
  }
  layer.batchDraw();
};
// 初始化Canvas
onMounted(() => {
  const { clientWidth, clientHeight } = canvasRef.value || {
    clientWidth: 0,
    clientHeight: 0
  };
  console.log("clientWidth", clientWidth, "clientHeight", clientHeight);
  stage = new Konva.Stage({
    container: "canvas",
    width: clientWidth,
    height: clientHeight
  });
  stage.add(layer);
  // 舞台点击事件需要等stage初始化后绑定
  stage.on("click", e => {
    if (e.target === stage) {
      hideHandles();
    }
  });

  // stage.on("click tap", (e) => {
  //   console.log('stage click', e);
  //   const dom = e.target
  //   console.log('dom', dom.getType())
  //   if (dom.getType() === "Shape") {//点击的是图形，Stage是画布，清空
  //     tr.nodes([dom])
  //   } else {
  //     tr.nodes([])
  //   }
  // })

  // const selectionRect = new Konva.Rect({
  //   fill: "rgba(0,0,255,0.1)",

  //   visible: false,
  //   stroke: "rgba(0,0,255,0.5)",
  //   strokeWidth: 1,
  // })
  // layer.add(selectionRect)
  // layer.add(tr)

  // init();
});
</script>

<style lang='scss' scoped>
.index {
  // padding: 20px;

  .canvas {
    background-color: #eee;
    border: 1px solid #666;
    height: calc(50vh);
  }
}
</style>
